import React, { useContext, useEffect, useState } from 'react'
import { Modal, Trigger } from '@kedacom/react-next'
import { usePopupVisible } from '@/hooks/usePopupVisible'
import { useCompanyInfo, useNotices } from './hook'
import { AppContext } from '@/pages/App/context'
import { quitLogin } from '@/utils/common'
import '@/static/js/userBehavior.js'
import {
	StyledWrap,
	StyledHeader,
	StyledHeaderRight,
	StyledHeaderLeft,
	CompanyLogoIcon,
	SplitIcon,
	SettingIcon,
	ExitIcon,
	StyledSettingWrap,
	StyledNotifyWrap,
	WarningIcon,
	ClearIcon,
	MsgIcon,
	MsgIconGif,
	ReadyIcon,
} from './style'
import Avatar from './Avatar'
import { useLocation, useNavigate } from 'react-router-dom'
import { info } from '../Notify'
import { ReconnectingWebSocketProps } from '@/utils/connectEXE'
import '@/static/js/userBehavior.js'
import { AboutBrand } from '../AboutBrand'
/*
没用到
*/
interface StatusType {
	SMC_APPLY_NOPASS: string
	SMC_APPLY_PASS: string
	SMC_ALARM: string
	SAC_ALARM: string
	SMC_APPROVE: string
}
export const status: StatusType = {
	SMC_APPLY_NOPASS: '#d21e1e',
	SMC_APPLY_PASS: '#09a206',
	SMC_ALARM: '',
	SAC_ALARM: '',
	SMC_APPROVE: '',
}
const statusText: StatusType = {
	SMC_APPLY_NOPASS: '已拒绝',
	SMC_APPLY_PASS: '已通过',
	SMC_ALARM: '',
	SAC_ALARM: '',
	SMC_APPROVE: '',
}
export default function Header() {
	/*
	isDialogShow
	关于弹窗是否展示
	*/
	const [isDialogShow, setDialogShow] = useState<boolean>(false)
	/*
	isOpen   消息icon pop是否展开 
	*/
	const [isOpen, setIsOpen] = useState<boolean>(false)
	/*
	counter 数量
	*/
	const [counter, setCounter] = useState<number>(0)
	let interValTime: NodeJS.Timer | null = null
	let ids: string = ''
	/*
	useNavigate() 路由跳转
	*/
	const navigate = useNavigate()
	/*
	settingPopVisible 设置icon的pop是否出现
	hideSettingPop 隐藏pop
	showSettingPop 展示pop
	*/
	const [settingPopVisible, showSettingPop, hideSettingPop] = usePopupVisible(false)
	/*
	hasNew 有新消息
	noticeList 消息数据
	noAlert
	setStateReady 接口请求获得下拉数据
	hadDelete 清除
	clearNotice 删除消息列表
	backToHome 返回home页
	exitSystem 退出系统
	hadAlert  接口请求--标记已提醒
	*/
	const { hasNew, noticeList, noAlert, setStateReady, hadDelete, clearNotice, backToHome, exitSystem, hadAlert } =
		useNotices()
	const AppData = useContext(AppContext)
	/*
	userInfo 用户信息
	*/
	const userInfo = AppData.user
	/*
	useLocation() 获取当前 location 信息
	*/
	let { pathname } = useLocation()
	/*
	version 版本信息  科达视频会议管理系统 V.8 · 机密   
	*/
	const [version, setVersion] = useState('')
	/*
	useEffect/AppData.system

	initUsbBehavior  检查ukey状态 
	setVersion 设置版本信息
	*/
	useEffect(() => {
		// systemSecurityLevel 防护要求 integer	系统密级： 0-未配置 1-秘密 2-机密一般 3-机密增强
	
		if (AppData.system.systemSecurityLevel === 3) {
			initUsbBehavior(AppData.system.systemSecurityLevel)
		}
		setVersion(AppData.system.appVersion?.substring(0, AppData.system.appVersion?.indexOf('.') + 2) || '')
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [AppData.system])
	/*
	useEffect/[]

	alarmEventListen 一直在请求这个接口，涉密系统，要求关闭浏览器之后，退出登录
	*/
	useEffect(() => {
		if (window.__userBehavior__) {
			window.__userBehavior__.alarmEventListen({})
		}
	}, [])
	/*
	initUsbBehavior  检查ukey状态
	*/
	const initUsbBehavior = (systemSecurityLevel: number) => {
		if (window.__userBehavior__ && window.__userBehavior__.checkUSBBehavior) {
			window.__userBehavior__.checkUSBBehavior({
				systemSecurityLevel: systemSecurityLevel,
				onError: () => {
					quitLogin()
				},
			})
		}
	}
	useEffect(() => {
		console.log(AppData)
	}, [AppData])
	/*
	useEffect/noAlert
	useEffect/counter 
	*/
	useEffect(() => {
		if (noAlert.length !== 0) {
			// eslint-disable-next-line react-hooks/exhaustive-deps
			/*
			let interValTime: NodeJS.Timer | null = null
			*/
			interValTime = setTimeout(() => {
				// eslint-disable-next-line react-hooks/exhaustive-deps
				ids = ''
				/*
				1.setTimeoutNotice
				*/
				setTimeoutNotice()
				/*
				2.setCounter
				*/
				setCounter(counter + 1)

				/*
				3.isOpen 
				true   消息icon pop展开
					1.setStateReady 接口请求获得下拉数据
					2.clearTimeout 清空定时器

				false  消息icon pop关闭
					1.hadAlert  接口请求--标记已提醒
				*/
				if (isOpen) {
					setStateReady()
					clearTimeout(Number(interValTime))
				} else if (ids.length !== 0) {
					hadAlert(ids)
				}
			}, 11 * 1000)
		}
		return () => {
			clearTimeout(Number(interValTime))
		}
	}, [noAlert, counter])

	/*
	companyInfo 公司信息，用于头部不同品牌的信息展示
	*/
	const { companyInfo } = useCompanyInfo()
	/*
	toggleSetting 点击设置按钮，出现下拉框

	settingPopVisible 设置icon的pop是否出现
	hideSettingPop 隐藏pop
	showSettingPop 展示pop

	typescript 点击事件 
	(e: React.MouseEvent<Element, MouseEvent>) => {...}

	*/
	const toggleSetting = (e: React.MouseEvent<Element, MouseEvent>) => {
		settingPopVisible ? hideSettingPop(e) : showSettingPop(e)
	}

	// 消息通知冒泡函数
	const setTimeoutNotice = () => {
		for (let i = 0; i < 5; i++) {
			if (counter * 5 + i >= noAlert.length) {
				// clearTimeout(Number(interValTime))
				break
			}
			ids += noAlert[counter * 5 + i]['moid'] + ','
			setTimeout(() => {
				// children  是否自动隐藏  typeText  停留时间
				// error(noAlert[counter * 6 + i], true, noAlert[counter * 6 + i]['title'], 6)
				if (noAlert[counter * 5 + i]['type'] === 'SAC_ALARM') {
					info(noAlert[counter * 5 + i], true, '', '待查看', 6)
				}
			}, 800 * i)
		}
	}
	/*
	toggleNotice 点击消息icon，pop是否出现

	1.如果展开
	setStateReady 接口请求获得下拉数据 
	clearTimeout 清空定时器
	*/
	const toggleNotice = (isOpen: boolean) => {
		setIsOpen(isOpen)

		if (isOpen) {
			setStateReady()
			clearTimeout(Number(interValTime))
		}
	}
	// 数据状态 是否展示，是否已读
	// 每次提示展示最多5个，
	// 删除/全部清除 即标记已读
	const onClickItem = (toTarget: string, e: React.MouseEvent<Element, MouseEvent>) => {
		hideSettingPop(e)
		if (toTarget === 'about') {
			/*
			点击关于，出现弹窗
			*/
			setDialogShow(true)
		} else {
			if (pathname !== toTarget) {
				if (toTarget === '/configuration') {
					navigate(`${toTarget}?type=modification`)
				} else {
					const resetUrl = AppData.system.systemSecurityLevel === 3 ? `/set/pin` : `/set/password`
					navigate(`${resetUrl}`)
				}
			}
		}
	}
	return (
		<StyledWrap>
			<StyledHeader>
				<StyledHeaderLeft onClick={backToHome}>
					<div className="home-header-company-icon"></div>
					<SplitIcon></SplitIcon>
					<div className="title">
						{/* 
						systemName 科达视频会议管理系统 
						version  V.8
						*/}
						{companyInfo.systemName + ' ' + version}
						{AppData.system.systemSecurity === 2
							? ' · 机密'
							: AppData.system.systemSecurity === 1
							? ' · 秘密'
							: ' · 未配置'}
					</div>
				</StyledHeaderLeft>
				<StyledHeaderRight>
					<div className="userInfo">
						<span className="avatar">
							<Avatar portrait={userInfo?.portraitBit40} />
						</span>
						<span title={userInfo?.name}>{userInfo?.name}</span>
					</div>
					<Trigger
						trigger={['click']}
						popupAlign={{
							points: ['tc', 'bc'],
							offset: [-90, 300],
						}}
						onOpen={() => {
							toggleNotice(true)
						}}
						onClose={() => {
							toggleNotice(false)
						}}
						popup={
							<StyledNotifyWrap>
								<div className="notify-top">
									<span className="notify-title">通知消息</span>
									<span className="notify-clear-all" onClick={() => clearNotice()}>
										清空
									</span>
								</div>
								<div className="notify-list">
									{noticeList.length !== 0 && (
										<ul>
											{noticeList.map((item, index) => {
												return (
													<li className="notify-info-li" key={index}>
														<WarningIcon></WarningIcon>
														<div className="notify-info">
															<a href={`#/alarm`} title={item.title}>
																<div className="notify-type-title">
																	您有告警消息，请查看
																</div>
																{/* smc显示归类之后的条数 */}
																{/* <div className="notify-type-count">
																	{item.data ? '(' + item.data.length + ')' : ''}
																</div> */}
															</a>
														</div>
														{/* </div> */}
														<ClearIcon
															className="clear-notify"
															title="删除消息"
															onClick={() => hadDelete(item.moid)}
														></ClearIcon>
													</li>
												)
											})}
										</ul>
									)}
									{noticeList.length === 0 && <div className="no-notice">暂无消息</div>}
								</div>
							</StyledNotifyWrap>
						}
					>
						{/* 有新消息且面板为关闭才会闪动 */}
						{hasNew > 0 && !isOpen ? (
							<MsgIconGif>
								<ReadyIcon></ReadyIcon>
							</MsgIconGif>
						) : (
							<MsgIcon></MsgIcon>
						)}
					</Trigger>
					<Trigger
						trigger={['click']}
						popupAlign={{
							offset: [0, 10],
						}}
						popup={
							<StyledSettingWrap>
								<span>
									<ul>
										<li>
											<p onClick={(e) => onClickItem('set', e)}>个人设置</p>
										</li>
									</ul>
									<ul>
										<li>
											<p
												className={`popup_item`}
												onClick={() => {
													let isWin =
														window.navigator.platform === 'Win32' ||
														window.navigator.platform === 'Windows'
													let type = isWin ? '0' : '1'
													window.location.href = `/web/portal/system/ca?type=${type}`
												}}
											>
												CA证书下载
											</p>
										</li>
									</ul>
									<ul>
										<li>
											<p
												onClick={() => {
													window.open('/sac/brand/index/help/default.html', 'newWindow')
												}}
											>
												帮助信息
											</p>
										</li>
									</ul>
									<ul>
										<li>
											<p
												onClick={() => {
													setDialogShow(true)
												}}
											>
												关于
											</p>
										</li>
									</ul>
								</span>
							</StyledSettingWrap>
						}
					>
						<SettingIcon onClick={toggleSetting}></SettingIcon>
					</Trigger>

					<ExitIcon onClick={exitSystem}></ExitIcon>
				</StyledHeaderRight>
				<Modal
					open={isDialogShow}
					title="关于"
					onCancel={() => setDialogShow(false)}
					needFooter={false}
					width={400}
					height={300}
				>
					<AboutBrand></AboutBrand>
				</Modal>
			</StyledHeader>
		</StyledWrap>
	)
}
